package legumes.shared.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Id;

import com.googlecode.objectify.annotation.Serialized;

public class Order implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Id private long id = -1;
	private long date;
	private String customerId;
	private String customerName;
	@Serialized private List<OrderPart> orderParts;
	
	transient private List<OrderListener> listeners;

	public Order() {
		orderParts = new ArrayList<OrderPart>();
		listeners = new ArrayList<OrderListener>();
	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName_) {
		customerName = customerName_;
	}

	/**
	 * @return the customerId
	 */
	public String getCustomerId() {
		return customerId;
	}

	/**
	 * @param customerId
	 *            the customerId to set
	 */
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	
	public void addListener(OrderListener l_) {
		listeners.add(l_);
	}

	public void removeEmptyOrderParts() {
		orderParts.iterator();
		
		for (int i = orderParts.size() - 1; i <= 0; i--) {
			if (((List<OrderPart>)orderParts).get(i).isEmpty()) {
				orderParts.remove(i);
			}
		}
	}

	public void plus(Order order_) {
		if (order_ == null) {
			return;
		}
		for (OrderPart op : order_.getOrderParts()) {
			if (!op.isEmpty()) {
				((List<OrderPart>)orderParts).add(0, op);
			}
		}
	}

	public void removeListener(OrderListener l_) {
		listeners.remove(l_);
	}

	public void fireContentChanged() {
		for (OrderListener l : listeners) {
			l.onContentChanged(this);
		}
	}

	public List<OrderPart> getOrderParts() {
		return ((List<OrderPart>)orderParts);
	}

	public void setOrderParts(List<OrderPart> orderParts_) {
		orderParts = orderParts_;
	}

	public long getDate() {
		return date;
	}

	public void setDate(long date) {
		this.date = date;
	}

	@Override
	public boolean equals(Object obj) {
		return id == ((Order) obj).getId();
	}

	public void addOrderPart(OrderPart lc_) {
		orderParts.add(lc_);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("[Order id=").append(getId()).append(" customerId=").append(
				getCustomerId()).append(" orderParts=");
		for (OrderPart lc : getOrderParts()) {
			sb.append(lc.toString()).append(" ");
		}
		sb.append("]");
		return sb.toString();
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public Cost computePrice() {
		Cost cost = new Cost();
		for (OrderPart op : orderParts) {
			cost.plus(op.computePrice());
		}
		return cost;
	}

}
